const fs = require('fs');
const path = require('path');

class DocumentAnalyzer {
    constructor(configPath) {
        this.config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
        this.analysis = {
            totalFiles: 0,
            duplicateFiles: [],
            outdatedFiles: [],
            redundantFiles: [],
            keepFiles: [],
            archiveDirectories: [],
            deleteFiles: [],
            filesByType: {},
            sizeAnalysis: {},
            lastModified: {}
        };
    }

    async analyzeDocuments() {
        console.log('开始分析文档结构...');
        
        const docsPath = this.config.paths.docsRoot;
        await this.scanDirectory(docsPath);
        
        this.classifyFiles();
        this.generateReport();
        
        return this.analysis;
    }

    async scanDirectory(dirPath, relativePath = '') {
        const items = fs.readdirSync(dirPath);
        
        for (const item of items) {
            const fullPath = path.join(dirPath, item);
            const relativeItemPath = path.join(relativePath, item);
            
            // 跳过doc-cleanup目录
            if (item === 'doc-cleanup') continue;
            
            const stats = fs.statSync(fullPath);
            
            if (stats.isDirectory()) {
                await this.scanDirectory(fullPath, relativeItemPath);
            } else if (stats.isFile()) {
                this.analyzeFile(fullPath, relativeItemPath, stats);
            }
        }
    }

    analyzeFile(fullPath, relativePath, stats) {
        this.analysis.totalFiles++;
        
        const ext = path.extname(relativePath).toLowerCase();
        const fileName = path.basename(relativePath);
        const fileSize = stats.size;
        const lastModified = stats.mtime;
        
        // 按类型分类
        if (!this.analysis.filesByType[ext]) {
            this.analysis.filesByType[ext] = [];
        }
        this.analysis.filesByType[ext].push({
            path: relativePath,
            size: fileSize,
            lastModified: lastModified
        });
        
        // 记录文件信息
        this.analysis.lastModified[relativePath] = lastModified;
        this.analysis.sizeAnalysis[relativePath] = fileSize;
        
        // 检查是否为重复文件
        this.checkDuplicates(fileName, relativePath);
        
        // 检查是否为过时文件
        this.checkOutdated(fileName, relativePath, lastModified);
    }

    checkDuplicates(fileName, relativePath) {
        // 检查FINAL_开头的重复报告
        if (fileName.startsWith('FINAL_')) {
            const existing = this.analysis.duplicateFiles.find(f => 
                path.basename(f.path).startsWith('FINAL_') && 
                f.path !== relativePath
            );
            if (existing) {
                this.analysis.duplicateFiles.push({
                    path: relativePath,
                    type: 'final_report_duplicate',
                    reason: '多个FINAL报告文件'
                });
            }
        }
        
        // 检查其他重复模式
        const patterns = [
            { prefix: 'PROTOTYPE_', type: 'prototype_duplicate' },
            { prefix: 'UI_', type: 'ui_duplicate' },
            { prefix: 'ACCEPTANCE_', type: 'acceptance_duplicate' }
        ];
        
        patterns.forEach(pattern => {
            if (fileName.startsWith(pattern.prefix)) {
                const existing = this.analysis.duplicateFiles.find(f => 
                    path.basename(f.path).startsWith(pattern.prefix) && 
                    f.path !== relativePath
                );
                if (existing) {
                    this.analysis.duplicateFiles.push({
                        path: relativePath,
                        type: pattern.type,
                        reason: `多个${pattern.prefix}文件`
                    });
                }
            }
        });
    }

    checkOutdated(fileName, relativePath, lastModified) {
        const now = new Date();
        const daysDiff = (now - lastModified) / (1000 * 60 * 60 * 24);
        
        // 超过30天未修改的文件标记为可能过时
        if (daysDiff > 30) {
            this.analysis.outdatedFiles.push({
                path: relativePath,
                lastModified: lastModified,
                daysSinceModified: Math.floor(daysDiff),
                reason: '长时间未修改'
            });
        }
        
        // 特定的过时文件模式
        const outdatedPatterns = [
            'UI_ISSUES_ANALYSIS.md',
            'UI_REPAIR_',
            'AUTOMATION_CONFIG.md',
            'MAINTENANCE_GUIDE.md',
            'NAVIGATION.md',
            'QUALITY_CHECKLIST.md',
            'VERSION_CONTROL_GUIDE.md'
        ];
        
        outdatedPatterns.forEach(pattern => {
            if (fileName.includes(pattern)) {
                this.analysis.outdatedFiles.push({
                    path: relativePath,
                    lastModified: lastModified,
                    reason: '已识别为过时文件模式'
                });
            }
        });
    }

    classifyFiles() {
        console.log('分类文件...');
        
        // 根据配置分类文件
        this.analysis.deleteFiles = this.config.cleanup.deleteFiles.filter(file => {
            const fullPath = path.join(this.config.paths.docsRoot, file);
            return fs.existsSync(fullPath);
        });
        
        this.analysis.archiveDirectories = this.config.cleanup.archiveDirectories.filter(dir => {
            const fullPath = path.join(this.config.paths.docsRoot, dir);
            return fs.existsSync(fullPath);
        });
        
        // 标记保留的文件和目录
        this.config.cleanup.keepDirectories.forEach(dir => {
            const fullPath = path.join(this.config.paths.docsRoot, dir);
            if (fs.existsSync(fullPath)) {
                this.analysis.keepFiles.push({
                    path: dir,
                    type: 'keep_directory',
                    reason: '配置中标记为保留'
                });
            }
        });
    }

    generateReport() {
        const reportPath = path.join(this.config.paths.workingDir, 'analysis', 'document-analysis-report.json');
        
        const report = {
            timestamp: new Date().toISOString(),
            summary: {
                totalFiles: this.analysis.totalFiles,
                duplicateCount: this.analysis.duplicateFiles.length,
                outdatedCount: this.analysis.outdatedFiles.length,
                deleteCount: this.analysis.deleteFiles.length,
                archiveCount: this.analysis.archiveDirectories.length
            },
            details: this.analysis,
            recommendations: this.generateRecommendations()
        };
        
        fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
        console.log(`分析报告已生成: ${reportPath}`);
        
        // 生成人类可读的报告
        this.generateHumanReadableReport(report);
    }

    generateRecommendations() {
        const recommendations = [];
        
        if (this.analysis.duplicateFiles.length > 0) {
            recommendations.push({
                type: 'cleanup',
                priority: 'high',
                action: '删除重复文件',
                files: this.analysis.duplicateFiles.map(f => f.path)
            });
        }
        
        if (this.analysis.outdatedFiles.length > 0) {
            recommendations.push({
                type: 'archive',
                priority: 'medium',
                action: '归档过时文件',
                files: this.analysis.outdatedFiles.map(f => f.path)
            });
        }
        
        if (this.analysis.archiveDirectories.length > 0) {
            recommendations.push({
                type: 'archive',
                priority: 'high',
                action: '归档完成的项目目录',
                directories: this.analysis.archiveDirectories
            });
        }
        
        return recommendations;
    }

    generateHumanReadableReport(report) {
        const reportPath = path.join(this.config.paths.workingDir, 'analysis', 'document-analysis-summary.md');
        
        let content = `# 文档分析报告\n\n`;
        content += `生成时间: ${report.timestamp}\n\n`;
        
        content += `## 概要\n\n`;
        content += `- 总文件数: ${report.summary.totalFiles}\n`;
        content += `- 重复文件: ${report.summary.duplicateCount}\n`;
        content += `- 过时文件: ${report.summary.outdatedCount}\n`;
        content += `- 待删除文件: ${report.summary.deleteCount}\n`;
        content += `- 待归档目录: ${report.summary.archiveCount}\n\n`;
        
        if (report.details.duplicateFiles.length > 0) {
            content += `## 重复文件\n\n`;
            report.details.duplicateFiles.forEach(file => {
                content += `- ${file.path} (${file.reason})\n`;
            });
            content += `\n`;
        }
        
        if (report.details.outdatedFiles.length > 0) {
            content += `## 过时文件\n\n`;
            report.details.outdatedFiles.forEach(file => {
                content += `- ${file.path} (${file.reason})\n`;
            });
            content += `\n`;
        }
        
        if (report.details.deleteFiles.length > 0) {
            content += `## 待删除文件\n\n`;
            report.details.deleteFiles.forEach(file => {
                content += `- ${file}\n`;
            });
            content += `\n`;
        }
        
        if (report.details.archiveDirectories.length > 0) {
            content += `## 待归档目录\n\n`;
            report.details.archiveDirectories.forEach(dir => {
                content += `- ${dir}\n`;
            });
            content += `\n`;
        }
        
        content += `## 建议操作\n\n`;
        report.recommendations.forEach(rec => {
            content += `### ${rec.action} (优先级: ${rec.priority})\n\n`;
            if (rec.files) {
                rec.files.forEach(file => {
                    content += `- ${file}\n`;
                });
            }
            if (rec.directories) {
                rec.directories.forEach(dir => {
                    content += `- ${dir}\n`;
                });
            }
            content += `\n`;
        });
        
        fs.writeFileSync(reportPath, content);
        console.log(`可读报告已生成: ${reportPath}`);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    const configPath = path.join(__dirname, 'config.json');
    const analyzer = new DocumentAnalyzer(configPath);
    
    analyzer.analyzeDocuments()
        .then(analysis => {
            console.log('文档分析完成!');
            console.log(`总文件数: ${analysis.totalFiles}`);
            console.log(`重复文件: ${analysis.duplicateFiles.length}`);
            console.log(`过时文件: ${analysis.outdatedFiles.length}`);
        })
        .catch(error => {
            console.error('分析过程中出错:', error);
            process.exit(1);
        });
}

module.exports = DocumentAnalyzer;